package com.itbupt.eat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itbupt.eat.common.CustomException;
import com.itbupt.eat.entity.Category;
import com.itbupt.eat.entity.Dish;
import com.itbupt.eat.entity.Setmeal;
import com.itbupt.eat.mapper.CategoryMapper;
import com.itbupt.eat.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * @Author BUPT-Dingchang
 * @Create 2024/4/29 17:45
 * ClassName: CategoryServiceImpl
 * Description:
 */

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    // 注入菜品业务层
    @Lazy
    @Autowired
    private DishServiceImpl dishService;

    // 注入套餐业务层
    @Autowired
    private SetmealServiceImpl setmealService;

    // 分页查询
    @Override
    public Page<Category> getPage(Long currentPage, Long pageSize) {
        // 1. 创建条件查询构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();

        // 2. 根据显示顺序排序
        wrapper.orderByAsc(Category::getSort);

        // 3. 创建分页构造器
        Page<Category> page = new Page<>(currentPage, pageSize);

        return page(page, wrapper);
    }

    /**
     * 根据id删除分类
     * 删除分类时，需要判断分类下是否有关联的菜品或套餐
     * @param id 分类id
     * @return  是否删除成功
     */
    @Override
    public boolean remove(Long id) {
        // 1. 查询当前分类是否关联了菜品，如果关联了菜品，抛出一个业务异常
        // 1.1. 创建条件查询构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        // 1.2. 设置查询条件--分类id
        wrapper.eq(Dish::getCategoryId, id);
        // 1.3. 返回查询结果的总数
        int dishCount = dishService.count(wrapper);
        // 1.4. 如果菜品总数大于0，说明分类下有关联的菜品
        if(dishCount > 0) {
            throw new CustomException("该分类关联了菜品，无法删除");
        }

        // 2. 查询是否关联了套餐，如果关联了套餐，抛出一个业务异常
        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
        setmealWrapper.eq(Setmeal::getCategoryId, id);
        int setmealCount = setmealService.count(setmealWrapper);

        if(setmealCount > 0) {
            throw new CustomException("该分类关联了套餐，无法删除");
        }

        // 3. 如果没有关联的菜品和套餐，删除分类
        return removeById(id);
    }
}
